package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 获取短信验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();

        if(!StringUtils.isEmpty(phone)){
            // 来一个四位验证码 2 存下来
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code:{}",code);
            // 使用redis 来缓存数据
//            session.setAttribute(phone,code);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success("验证码发送成功");
        }
        return R.error("手机短信发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        log.info(map.toString());

        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        // 使用 redis 来读取 验证码缓存

//        Object codeInSession = session.getAttribute(phone);
        Object codeInSession = redisTemplate.opsForValue().get(phone);

        // 判断短信是否一样
        if(codeInSession!=null&& codeInSession.equals(code)){
            LambdaQueryWrapper<User> lam=new LambdaQueryWrapper<>();
            lam.eq(User::getPhone,phone);
            User one = userService.getOne(lam);
            if(one==null){
                one = new User();
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }
            session.setAttribute("user",one.getId());
            redisTemplate.delete(phone); // 登录成功 删除验证码
            return R.success(one);
        }
        return R.error("短信发送失败");



    }
}